#include <stdio.h>

#include "queue.h"

//return 1 if empty
int queueEmpty(struct queue* q)
{
	if(q->front == (q->rear % q->len)) {
        return 1;
    }
	return 0;
}

//return 1 if full
int queueFull(struct queue* q)
{
	if (((q->rear + 1) % q->len) == q->front) {
		return 1;
	}
	return 0;
}


//return rear index
//rear point to next empty room
int enQueue(SELemType *ary, struct queue* q, SELemType data)
{
	if (queueFull(q)) {
		printf("queue is full");
		return q->rear;
	}

	ary[q->rear] = data;
	q->rear = (q->rear + 1) % q->len;
    return q->rear;
}

//return front value of queue
//front point to queue head
SELemType deQueue(SELemType *ary, struct queue* q)
{
	SELemType ret;

	ret = ary[q->front];
    if(queueEmpty(q)) {
        printf("queue is empty");
        return ret;
    }
    q->front = (q->front + 1) % q->len;
    return ret;
}

void initQueue(struct queue* q, unsigned int maxLen)
{
	q->front = 0;
	q->rear = 0;
	q->len = maxLen;
}

void destroyQueue(struct queue* q)
{
	initQueue(q, 0);
}

unsigned int queueLength(struct queue* q)
{
	return q->len;
}

SELemType getQueueHead(struct queue* q)
{
	return q->front;
}


void test_queue(void)
{
	struct queue sq;
	SELemType i;
	int index;

	SELemType ary[QUEUE_SIZE];
	initQueue(&sq, QUEUE_SIZE);

	printf("enque:   ");
	for ( i = 1; i < 20; i++) {
		printf("%d ", i);
		enQueue(ary, &sq, i);
	}
	printf("\ndequeue: ");

	for ( i = 1; i < 20; i++) {
		index = deQueue(ary, &sq);
		printf("%d ", index);
	}
	printf("\n\n");

	destroyQueue(&sq);
}

int main(int argc, char** argv)
{
	test_queue();
	return 0;
}
